import { reactive, ref } from "vue";
import { ElForm } from 'element-plus';
import { DailogModel } from "@/type/BaseType";
import { EditType, Title } from "@/type/BaseEnum"
import userInstance from '@/hooks/userInstance'
import { AddMenuModel } from "@/api/menu/menuModel";
import { SelectNode } from '@/api/dept/DeptModel';

export default function addMenu(dailog:DailogModel,onShow, onClose,emit) {
    const { global } = userInstance()
    // 表单的ref属性
    const formDataRef = ref<InstanceType<typeof ElForm>>()
    // 表单绑定的数据
    const formData = reactive<AddMenuModel>({
        id: '',
        editType: '', // 新增/编辑
        type: '', // 菜单类型
        parentId: '',
        parentName: '',
        label: '',
        icon: '',
        name: '',
        path: '',
        url: '',
        code: '',
        open: false,
        orderNum: ''
    })
    // 表单验证规则
    const rules = reactive({
        type: [{
            required: true,
            message: '请输入菜单类型',
            trigger: 'change'
        }],
        parentName: [{
            required: true,
            message: '请选择上级菜单',
            trigger: 'change'
        }],
        label: [{
            required: true,
            message: '请填写菜单名称',
            trigger: 'change'
        }],
        name: [{
            required: true,
            message: '请填写路由名称',
            trigger: 'change'
        }],
        path: [{
            required: true,
            message: '请填写路由路径',
            trigger: 'change'
        }],
        url: [{
            required: true,
            message: '请填写组件路径',
            trigger: 'change'
        }],
        code: [{
            required: true,
            message: '请填写权限字段',
            trigger: 'change'
        }],
        icon: [{
            required: true,
            message: '请填写图标',
            trigger: 'change'
        }]
    })
    // 弹框展示
    const show111 = (type: string, row) => {
        // 设置弹框的属性
        dailog.height = 200
        type === EditType.ADD ? dailog.title = Title.ADD : dailog.title = Title.EDIT
        onShow()
        // 清空表单
        global.$restForm(formDataRef.value,formData)
        // 如果是编辑，要把编辑的数据复制到表单绑定的formData里面
        if(type === EditType.EDIT) {
            // 回显数据 把row复制到formData
            global.$objCopy(row,formData)
        }
        // 设置是新增还是编辑
        formData.editType = type
    }
    // 弹框确定
    const confirm = () => {
        formDataRef.value?.validate(valid => {
            console.log(valid)
            if(valid) {
                emit('save',formData)
                onClose()
            }
        })
    }
    // 选中上级的数据
    const select = (node:SelectNode) => {
        console.log('父组件取到值===', node)
        formData.parentId = node.id
        formData.parentName = node.name
    }
 
    return {
        formData,
        rules,
        formDataRef,
        show111,
        confirm,
        select
    }
}